package com.ruoyi.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.common.CommonValues;
import com.ruoyi.business.domain.BusStudentGrowth;
import com.ruoyi.business.domain.BusStudentGrowthItem;
import com.ruoyi.business.domain.BusStudentHonor;
import com.ruoyi.business.domain.BusUserComments;
import com.ruoyi.business.mapper.*;
import com.ruoyi.business.service.IBusSemesterService;
import com.ruoyi.business.service.IBusStudentGrowthItemService;
import com.ruoyi.business.service.IBusStudentGrowthService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.common.RedisKeyPrefix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 学生成长报告Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-10-22
 */
@Service
public class BusStudentGrowthServiceImpl extends ServiceImpl<BusStudentGrowthMapper,BusStudentGrowth> implements IBusStudentGrowthService
{
    @Autowired
    private BusStudentGrowthMapper busStudentGrowthMapper;

    @Autowired
    private IBusStudentGrowthItemService growthItemService;

    @Autowired
    private BusGradeMapper gradeMapper;

    @Autowired
    private IBusSemesterService busSemesterService;

    @Autowired
    private BusStudentGrowthItemMapper itemMapper;

    @Autowired
    private BusUserCommentsMapper commentsMapper;

    @Autowired
    private BusStudentHonorMapper honorMapper;

    @Autowired
    private IBusStudentGrowthItemService iGrowthItemService;

    @Autowired
    private IBusSemesterService iBusSemesterService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询学生成长报告
     * 
     * @param growthId 学生成长报告主键
     * @return 学生成长报告
     */
    @Override
    public BusStudentGrowth selectBusStudentGrowthByGrowthId(Long growthId)
    {
        return busStudentGrowthMapper.selectBusStudentGrowthByGrowthId(growthId);
    }

    /**
     * 查询学生成长报告列表
     * 
     * @param busStudentGrowth 学生成长报告
     * @return 学生成长报告
     */
    @Override
    public List<BusStudentGrowth> selectBusStudentGrowthList(BusStudentGrowth busStudentGrowth)
    {
        List<BusStudentGrowth> busStudentGrowths = busStudentGrowthMapper.selectBusStudentGrowthList(busStudentGrowth);
        busStudentGrowths.forEach((item)-> item.setStuName(busStudentGrowthMapper.getStudentName(item.getStudentId())));
        return busStudentGrowths;
    }

    /**
     * 新增学生成长报告
     * 
     * @param busStudentGrowth 学生成长报告
     * @return 结果
     */
    @Override
    public int insertBusStudentGrowth(BusStudentGrowth busStudentGrowth)
    {
//        busStudentGrowth.setCreateTime(DateUtils.getNowDate());
        return busStudentGrowthMapper.insertBusStudentGrowth(busStudentGrowth);
    }

    /**
     * 修改学生成长报告
     * 
     * @param busStudentGrowth 学生成长报告
     * @return 结果
     */
    @Override
    public int updateBusStudentGrowth(BusStudentGrowth busStudentGrowth)
    {
//        busStudentGrowth.setUpdateTime(DateUtils.getNowDate());
        return busStudentGrowthMapper.updateBusStudentGrowth(busStudentGrowth);
    }

    /**
     * 批量删除学生成长报告
     * 
     * @param growthIds 需要删除的学生成长报告主键
     * @return 结果
     */
    @Override
    public int deleteBusStudentGrowthByGrowthIds(Long[] growthIds)
    {
        return busStudentGrowthMapper.deleteBusStudentGrowthByGrowthIds(growthIds);
    }

    /**
     * 删除学生成长报告信息
     * 
     * @param growthId 学生成长报告主键
     * @return 结果
     */
    @Override
    public int deleteBusStudentGrowthByGrowthId(Long growthId)
    {
        return busStudentGrowthMapper.deleteBusStudentGrowthByGrowthId(growthId);
    }

    /**
     * 根据学生id查询其所有的成长报告id
     * @param stuId 学生id
     * @return 成长报告id列表
     */
    @Override
    public List<BusStudentGrowth> getGrowthsByStuId(Long stuId) {
        //先获取报告表中信息
        List<BusStudentGrowth> growths = busStudentGrowthMapper.
                getGrowthsByStuId(stuId);
        growths.forEach((item)-> item.setStuName(busStudentGrowthMapper.getStudentName(item.getStudentId())));
        //根据学期id获取学期信息
        growths.forEach((item)->{
            Map<String, Object> semesterName = busStudentGrowthMapper.getSemesterName(item.getSemesterId());
            item.setSemesterName(semesterName.get("semester_year").toString()+
                    semesterName.get("semester_name")
            );
            Date nowDate = DateUtils.getNowDate();
            if (nowDate.after(item.getReportStartEnd())) {
                item.setStatus("2");
            }
        });
        return growths;
    }
    @Override
    public List<Map<String, Integer>> getStudentGrowPace(Long gradeId, Long semesterId) {
        this.updateGrowthStatus();
        List<Map<String, List<String>>> growthStudentName = growthItemService.getGrowthStudentName(gradeId,semesterId);
        //模块mapModulePace
        Map<String, List<String>> map1 = growthStudentName.get(0);
        //总进度mapNameCountPace
        Map<String, List<String>> map2 = growthStudentName.get(1);
        //用来统计总的完成、进行中、未完成人数
        Map<String, Integer> mapModulePace=new HashMap<>();

        //用来统计总的完成、进行中、未完成人数
        Map<String, Integer> mapNameCountPace=new HashMap<>();
        Set<String> map1Keys = map1.keySet();
        Set<String> map2Keys = map2.keySet();
        for (String key:map1Keys) {
            List<String> list = map1.get(key);
            mapModulePace.put(key,list.size());
        }
        for (String key:map2Keys) {
            List<String> list = map2.get(key);
            mapNameCountPace.put(key,list.size());
        }
        //封装进度map
        List<Map<String, Integer>> Pace=new ArrayList<>();
        Pace.add(mapModulePace);
        Pace.add(mapNameCountPace);
        return Pace;
    }
    //依附在统计中更新学生成长报告的整体状态
    private void updateGrowthStatus(){
        //更新因时间截止触发定稿的状态
        busStudentGrowthMapper.getUnActiveGrowth();
        List<Long> all = gradeMapper.getAll();
        Long currentSemesterId = busSemesterService.getCurrentSemesterId();
        all.forEach((item)->{
            //获取学生的growthId
            Long growthId = busStudentGrowthMapper.
                    getStudentCurrentGrowthId(item, currentSemesterId);
            //通过growthId获取所有环节的状态
            List<Character> status = busStudentGrowthMapper.getStatus(growthId);
            status.forEach((c)->{
                if (c.equals('0')){
                    return;
                }
            });
            busStudentGrowthMapper.setStatus(growthId,'1');
        });
    }
    @Transactional
    @Override
    public void newGrowth(Date endTime) {
        Long currentSemesterId = busSemesterService.getCurrentSemesterId();
        redisTemplate.delete(RedisKeyPrefix.CURRENT_REPORT_FINISH_FLAG);
        redisTemplate.delete(RedisKeyPrefix.
                CURRENT_REPORT_FINISH_TIME+(currentSemesterId-1));
        //更新开启状态
        busSemesterService.updateStatus();
        //获取每个学生的id
        List<Long> all = gradeMapper.getAll();
        List<Long> unActiveIds = new ArrayList<>();

        all.forEach((id)->{
            BusStudentGrowth busStudentGrowth = new BusStudentGrowth();
            busStudentGrowth.setStudentId(id);
            busStudentGrowth.setSemesterId(currentSemesterId);
            Long studentCurrentGrowthId = busStudentGrowthMapper.
                    getStudentCurrentGrowthId(id, currentSemesterId);
            //导入学生中也包含生成成长报告,此处判断一下是否存在防止重复生成
            if (studentCurrentGrowthId != null){
                unActiveIds.add(studentCurrentGrowthId);
                busStudentGrowthMapper.updateReportStartEndInt(studentCurrentGrowthId,endTime);
            }else{
                createHonorAndComment(busStudentGrowth,endTime,id);
            }
        });
        //获取需要生成item的growthId
        List<Long> activeIds = busStudentGrowthMapper.
                getActiveId(currentSemesterId);
        //移除已生成过item的growthId
        activeIds.removeAll(unActiveIds);
        //未生成过成长报告
        activeIds.forEach((id)->{
            BusStudentGrowthItem busStudentGrowthItem = new BusStudentGrowthItem();
            busStudentGrowthItem.setGrowthId(id);
            for (String itemKey:CommonValues.ITEMS){
                if (itemKey.equals("我的荣誉") || itemKey.equals("学生素养报告单")){
                    busStudentGrowthItem.setStatus("1");
                }else{
                    busStudentGrowthItem.setStatus("0");
                }
                busStudentGrowthItem.setGrowthKey(itemKey);
                itemMapper.insertBusStudentGrowthItem(busStudentGrowthItem);
            }
        });
    }
    private void createHonorAndComment(BusStudentGrowth busStudentGrowth,Date endTime,Long id){
        busStudentGrowth.setReportStartTime(DateUtils.getNowDate());
        busStudentGrowth.setReportStartEnd(endTime);
        busStudentGrowth.setStatus("0");
        busStudentGrowthMapper.insertBusStudentGrowth(busStudentGrowth);
        BusStudentHonor busStudentHonor = new BusStudentHonor();
        busStudentHonor.setStudentId(id);
        honorMapper.insertBusStudentHonor(busStudentHonor);
        //查询班级id
        Long gradeId = gradeMapper.getGradeIdByStuId(id);
        //根据班级id查询其班主任id
        Long userId = gradeMapper.getUserIdByGradeId(gradeId);
        BusUserComments busUserComments = new BusUserComments();
        busUserComments.setStudentId(id);
        busUserComments.setStatus("0");
        busUserComments.setRemark("0");
        busUserComments.setUserId(userId);
        commentsMapper.insertBusUserComments(busUserComments);
    }
    @Override
    public boolean addStudentGrowth(Long StudentId) {
        //当年学年Id
        Long currentSemesterId = iBusSemesterService.getCurrentSemesterId();
        //创建Bean对象
        BusStudentGrowth busStudentGrowth = new BusStudentGrowth();
        busStudentGrowth.setStudentId(StudentId);
        busStudentGrowth.setSemesterId(currentSemesterId);


        //这部分用来新增学生时对于成长报告时间的操作--因为涉及到中途加入或者成长报告已经开启的学生的加入
        QueryWrapper<BusStudentGrowth> fixWrapper = new QueryWrapper<>();
        //需要当前学期的人
        fixWrapper.eq("semester_id",currentSemesterId);
        //并且随便拿一个时间不为空的
        fixWrapper.last("and report_start_time and report_start_end is not null limit 1");
        List<BusStudentGrowth> growths = this.list(fixWrapper);

        //如果这个集合为空则证明此学期还暂时未开放，所以直接可以时为空的没问题
        boolean saveStudentGrowth;
        if (growths.isEmpty()){
            //先存储报告表
             saveStudentGrowth = this.save(busStudentGrowth);
        }else {
            //这里是集合不为空，如果不为空  那么代表着本学期的成长报告项，已经被开启
            BusStudentGrowth item = growths.get(0);
            //所以现在就是获取这个时间的信息，从而更新我们这个新增的学生的成长报告
            busStudentGrowth.setReportStartTime(item.getReportStartTime());
            busStudentGrowth.setReportStartEnd(item.getReportStartEnd());
            saveStudentGrowth = this.save(busStudentGrowth);
        }
        //回调其方法，拿到这个学生本学期专属growthId
        LambdaQueryWrapper<BusStudentGrowth> busStudentGrowthWrapper = new LambdaQueryWrapper<>();
        busStudentGrowthWrapper.eq(BusStudentGrowth::getStudentId,StudentId);
        busStudentGrowthWrapper.eq(BusStudentGrowth::getSemesterId,currentSemesterId);
        BusStudentGrowth studentGrowth = this.getOne(busStudentGrowthWrapper);
        Long growthId = studentGrowth.getGrowthId();


        //创建成长报告基本项值
        String[] item=CommonValues.ITEMS;

        //用来记录项值添加是否成功
        int count = 0;
        for (String key : item) {
            //创建其项值对象
            BusStudentGrowthItem busStudentGrowthItem = new BusStudentGrowthItem();
            busStudentGrowthItem.setGrowthId(growthId);
            busStudentGrowthItem.setGrowthKey(key);
            busStudentGrowthItem.setStatus("0");
            boolean save = iGrowthItemService.save(busStudentGrowthItem);
            if (save){
                count++;
            }
        }
        return saveStudentGrowth && count >= 13;
    }

    @Override
    public int resetEndTime(Date date) {
        Long currentSemesterId = busSemesterService.getCurrentSemesterId();
        //删除缓存
        redisTemplate.delete(RedisKeyPrefix.CURRENT_REPORT_FINISH_FLAG);
        redisTemplate.delete(RedisKeyPrefix.
                CURRENT_REPORT_FINISH_TIME+(currentSemesterId-1));
        return busStudentGrowthMapper.resetEndTime(date,
                currentSemesterId);
    }

    @Override
    public Boolean growthNotIsCurrentSemester(Long growthId){
        Long semesterId = busStudentGrowthMapper.
                getSemesterIdByGrowthId(growthId);
        return !Objects.equals(busSemesterService.getCurrentSemesterId(), semesterId);
    }

    @Override
    public String getBeforeGrowth(Long growthId) {
        return busStudentGrowthMapper.getBeforeGrowth(growthId);
    }

    @Override
    public List<String> getGrowthResByStudentId(Long studentId,String itemKey) {
        return busStudentGrowthMapper.getGrowthResByStudentId(studentId,itemKey);
    }

}
